import { Sprite } from "@/sprites/Sprite.js";
import { ImageManager } from "@/managers/ImageManager.js";
import { config } from "@/managers/ConfigManager.js";

export class Sprite_Weapon extends Sprite {
    constructor() {
        super();
        this.anchor.set(0.5,1);
        this.x = -16;

        this._weaponImageId = 0;
        this._animationCount = 0;
        this._frameIndex = 0;
        
        this.visible=false;
    }

    setup(weaponImageId) {
        this._animationCount = 0;
        this._frameIndex = 0;
        if(this._weaponImageId!=weaponImageId){
            this._weaponImageId = weaponImageId;
            this.loadSource();
        }else{
            this.updateFrame();
        }
    }

    loadSource() {
        let pageId = Math.floor((this._weaponImageId - 1) / 12) + 1;
        this.visible=false;
        if (pageId >= 1) {
            ImageManager.loadSystem(`Weapons${pageId}`).then(source=>{
                this.source=source;
                this.visible=true;
                this.updateFrame();
            });
        }
    }

    update() {
        super.update();
        if (this.visible
            &&++this._animationCount >= config.animationSpeed) {
            this.updateFrame();
            this._animationCount = 0;
        }
    }

    updateFrame() {
        if (this._weaponImageId > 0) {
            let index = (this._weaponImageId - 1) % 12;
            let w = 96;
            let h = 64;
            let sy = index % 6;
            let sx = (index-sy)/2 + this._frameIndex ;

            this.setFrame(sx*w, sy*h, w, h);

            if (++this._frameIndex >= 3) {
                this._weaponImageId = 0;
                this.visible=false;
            }
        }
    }

    isPlaying() {
        return this._weaponImageId > 0;
    }
}